#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
import os
import json

base_dir = os.path.dirname(__file__)
def load_db(): 
    with open(os.path.join(base_dir, 'db.json'), 'rb') as fp:
        content = fp.read().decode()
    return json.loads(content)
db_data = load_db()

id_counter = 20000
def get_new_id():
    global id_counter
    id_counter += 1
    return id_counter

def DbQueryHandler(tag):
    data = []
    data = db_data[tag]
    class __Handler__(tornado.web.RequestHandler):
        def get(self):
            arg_id = self.get_argument('id', None)
            res = None
            if arg_id:
                arg_id = int(arg_id)
                for item in data:
                    if item['id'] == arg_id:
                        res = [item]
            if res is None:
                res = data
            self.write(json.dumps(res))
            
        def post(self):
            params = self.request.body.decode('utf-8')
            params = json.loads(params)
            params['id'] = get_new_id()
            data.append(params)
            self.write(json.dumps(params))
    return __Handler__

def DbAddHandler(tag):
    data = db_data[tag]
    class __Handler__(tornado.web.RequestHandler):
        def get(self):
            arg_id = self.get_argument('id', None)
            res = None
            if arg_id:
                arg_id = int(arg_id)
                for item in data:
                    if item['id'] == arg_id:
                        res = [item]
            if res is None:
                res = data
            self.write(json.dumps(res))
    return __Handler__
    

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

def make_app(settings):
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/user", DbQueryHandler('user')),
        (r"/user/add", DbAddHandler('user')),
        (r"/book", DbQueryHandler('book')),
    ], **settings)

if __name__ == "__main__":
    settings = {'static_hash_cache': False,
                'static_path': 'static',        # 静态文件（css,js,img）
                }
    port = 8888
    app = make_app(settings)
    app.listen(port)
    print('服务端口: %s' % port)
    tornado.ioloop.IOLoop.current().start()